package com.asia5b.a5mall.order.activity

import android.content.Intent
import androidx.recyclerview.widget.GridLayoutManager
import android.text.TextUtils
import android.view.View
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.asia5b.a5bmall.resource.ActCons
import com.asia5b.a5bmall.same.dialog.SelectBaseDialog
import com.asia5b.a5mall.middleware.event.OrderParcelEvent
import com.asia5b.a5mall.middleware.event.SelectAddressChange
import com.asia5b.a5mall.middleware.logic.viewmodel.order.OrderParcelActivityVM
import com.asia5b.a5mall.middleware.model.cart.TransModel
import com.asia5b.a5mall.middleware.model.member.AddressModel
import com.asia5b.a5mall.middleware.model.shop.AbsGoodsModel
import com.asia5b.a5mall.middleware.model.shop.OrderParcelDetailModel

import com.asia5b.a5mall.middleware.utils.*
import com.asia5b.a5mall.order.R
import com.asia5b.a5mall.order.adapter.OrderParcelGoodsAdapter
import com.asia5b.a5mall.order.databinding.ActivityOrderparcelBinding
import com.asia5b.a5bmall.same.dialog.ParcelAddressDialog
import com.asia5b.a5mall.middleware.base.SimpleActivity
import com.asia5b.a5mall.middleware.model.bean.*
import kotlinx.android.synthetic.main.activity_orderparcel.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * Created by zhangyuncai on 2020/3/10.
 * 申请打包
 */
@Route(path = ActCons.OrderParcelActivity)
class OrderParcelActivity : SimpleActivity<OrderParcelActivityVM, ActivityOrderparcelBinding>() {
    override val viewModelClazz: Class<OrderParcelActivityVM>
        get() = OrderParcelActivityVM::class.java

    override fun getDataBinding(): ActivityOrderparcelBinding {
        return ActivityOrderparcelBinding.inflate(layoutInflater)
    }

    override var sIsDark = true

    val localTransList = arrayListOf<TransModel>()

    //国际运输方式
    val interTransList = arrayListOf<TransModel>()

    val goods = arrayListOf<AbsGoodsModel>()
    val goodsRecyclerView by lazy { rv_orderplace_goods }
    val goodsAdapter = OrderParcelGoodsAdapter(goods)

    var orderParcelDetailModel: OrderParcelDetailModel? = null

    /**
     * 后台返回的
     */
    fun getWareHourseId(): Int {
        return orderParcelDetailModel?.address_list?.getOrNull(0)?.region_id ?: 0
    }

    fun isMingan(): Int {
        if (orderParcelDetailModel?.traits ?: true) {
            return 1
        }
        return 0
    }


    val ll_orderplace_address2 by lazy {
        ll_orderplace_address
    }


    override fun initView() {
        val parcelModelList = intent.getSerializableExtra("datas") as ArrayList<PostParcelBean>
        mViewModel.getPackList(parcelModelList)

        localTransList.clear()
        localTransList.add(TransModel().run {
            goodsName = getString(R.string.自提)
            id = 1
            this
        })
        localTransList.add(TransModel().run {
            goodsName = getString(R.string.派送到家)
            id = 2
            this
        })
        setAddressView(null)
        setInterTransferView(interTransList.getOrNull(0))
        setLocalTransferView(localTransList.getOrNull(0))

        goodsRecyclerView.run {
            layoutManager = GridLayoutManager(mActivity, 4)!!
            adapter = goodsAdapter
        }
    }


    /**
     * 设置地址
     */
    fun setAddressView(addressModel: AddressModel?) {
        ll_orderplace_address.addressModel = addressModel
    }

    fun setInterTransferList(transportations: ArrayList<TransModel>?) {
        interTransList.clear()
        if (!transportations.isNullOrEmpty()) {
            interTransList.addAll(transportations)
        }
        setInterTransferView(interTransList.getOrNull(0))
    }

    /**
     * 国际运输方式
     */
    fun setInterTransferView(transModel: TransModel?) {
        val orderPlaceMenuBean = OrderPlaceMenuBean(OrderPlaceItemEntity.OrderPlace_Transtype,
                getString(R.string.国际运输方式), getString(R.string.暂无可使用))
        if (transModel != null) {
            orderPlaceMenuBean.value = "${transModel?.goodsName}"
        }
        ll_orderplace_intertransfer.selectModel = transModel
        ll_orderplace_intertransfer.setMenuBean(orderPlaceMenuBean)
    }

    /**
     * 国际运输方式
     */
    fun setLocalTransferView(transModel: TransModel?) {
        val orderPlaceMenuBean = OrderPlaceMenuBean(OrderPlaceItemEntity.OrderPlace_Transtype,
                getString(R.string.本地运输方式), getString(R.string.暂无可使用))
        if (transModel != null) {
            orderPlaceMenuBean.value = "${transModel?.goodsName}"
        }
        ll_orderplace_localtransfer.selectModel = transModel
        ll_orderplace_localtransfer.setMenuBean(orderPlaceMenuBean)
    }

    /**
     * 商品
     */
    fun setGoodsView(orderParcelDetailModel: OrderParcelDetailModel?) {
        goods.clear()
        var goodsSize = 0
        orderParcelDetailModel?.express_list?.forEach {
            it.goods_list?.run {
                for (orderParcelGoodsBean in this) {
                    if (goods.size < 4) {
                        goods.add(orderParcelGoodsBean)
                    }
                    goodsSize++
                }
            }
        }
        goodsAdapter.notifyDataSetChanged()

        tv_orderparcel_ordersn.text = "${orderParcelDetailModel?.order_sn}"
        tv_orderparcel_ordergoodsnum.text = String.format(getString(R.string.共_数_件商品), "${goodsSize}")
    }

    override fun initEvent() {

        /**
         * 选择国际运输方式
         */
        ll_orderplace_intertransfer.setOnClickListener {
            showSelectDialog(SelectType.intertrans)
        }
        /**
         * 选择本地运输方式
         */
        ll_orderplace_localtransfer.setOnClickListener {
            showSelectDialog(SelectType.localtrans)
        }

        val onClickListener = View.OnClickListener {
            //            if (!address_list.isNullOrEmpty() && address_list!!.size > 1) {
//                push(ActCons.MemberAddressActivity, {
//                    it.withBoolean("order", true)
//                    it.withSerializable("datas", address_list!!)
//                }, requstCode = GlobalState.ORDER_CREATE_ADDRESS)
//            }

            if (!address_list.isNullOrEmpty() && address_list!!.size > 1) {
                val selectAddressModel = ll_orderplace_address.addressModel
                val dialog = ParcelAddressDialog(mActivity).run {
                    mDatas.addAll(address_list!!)
                    selectAddress = selectAddressModel
                    this
                }
                dialog.setSureClick<AddressModel> {
                    val addressId = ll_orderplace_address.addressModel?.addr_id ?: 0
                    val addressModel = it
                    if (addressModel.addr_id != addressId) {
                        mViewModel.getInterTranser(addressModel.addr_id, getWareHourseId(), isMingan())
                        setAddressView(addressModel)
                    }
                }
                dialog.show()
            }
        }
        /**
         * 修改地址
         */
        ll_orderplace_address.setOnClickListener(onClickListener)
        //打包详情
        cons_orderparcel_ordersn.setOnClickListener {
            startOrderParcelDetailActivity()
        }
        goodsRecyclerView.setOnClickListener {
            startOrderParcelDetailActivity()
        }
        goodsAdapter.setOnItemClickListener { adapter, view, position ->
            startOrderParcelDetailActivity()
        }
        //申请打包
        bt_orderplace_submit.setOnClickListener {
            submit()
        }
    }

    fun startOrderParcelDetailActivity() {
        orderParcelDetailModel?.run {
            val intent = Intent(mActivity, OrderParcelDetailActivity::class.java)
            intent.putExtra("data", this)
            startActivity(intent)
        }
    }

    override fun initData() {
    }

    fun submit() {
        val model = PostOrderParcelBean()
        model.order_sn = orderParcelDetailModel?.order_sn ?: ""

        orderParcelDetailModel?.ids?.run {
            if (this.size > 0) {
                model.ids = TextUtils.join(",", this)
            }
        }

        val addressModel = ll_orderplace_address.addressModel
        addressModel?.run {
            model.adder_id = this.addr_id
            model.house_id = getWareHourseId()
        }
        ll_orderplace_localtransfer.selectModel?.run {
            val transModel = this as TransModel
            model.shipping_id = transModel.id
        }
        ll_orderplace_intertransfer.selectModel?.run {
            val transModel = this as TransModel
            model.transport_type = transModel.transport_type
            model.fast_type = transModel.id
        }
        model.guarantee_price = (cb_orderplace_baoxian.isChecked).judge(1, 0)
        model.wood_price = (cb_orderplace_damujia.isChecked).judge(1, 0)
        model.protect = (cb_orderplace_tesubaohu.isChecked).judge(1, 0)
        model.labelling = (cb_orderplace_tiebiaoqian.isChecked).judge(1, 0)

        model.remark = tv_orderplace_remark.getText().toString()

        orderParcelDetailModel?.run {
            model.country_id = this.country_id
        }

        if (TextUtils.isEmpty(model.order_sn)) {
            dddLog("订单信息为空!!")
            return
        }
        if (TextUtils.isEmpty(model.ids)) {
            dddLog("订单信息为空!!")
            return
        }
        if (TextUtils.isEmpty(model.country_id)) {
            dddLog("订单信息为空!!")
            return
        }
        if (model.adder_id <= 0) {
            showMessage(getString(R.string.请选择地址))
            return
        }
        if (model.fast_type <= 0) {
            showMessage(getString(R.string.请选择国际运输方式))
            return
        }
        if (model.shipping_id <= 0) {
            showMessage(getString(R.string.请选择本地运输方式))
            return
        }
        mViewModel.orderParcel(model)
    }


    /**
     * 显示选择框
     */
    fun showSelectDialog(type: SelectType) {
        when (type) {
            SelectType.intertrans -> {
                var selectText = ll_orderplace_intertransfer.selectModel?.run {
                    this as SelectText
                }
                SelectBaseDialog(mActivity).apply {
                    title = getString(R.string.选择国际运输方式)
                    mDatas.addAll(interTransList)
                    this.selectText = selectText
                    this.setSureClick<SelectText> {
                        val select = it as TransModel
                        setInterTransferView(select)
                    }
                }.show()
            }
            SelectType.localtrans -> {
                var selectText = ll_orderplace_localtransfer.selectModel?.run {
                    this as SelectText
                }
                SelectBaseDialog(mActivity).apply {
                    title = getString(R.string.派送方式)
                    mDatas.addAll(localTransList)
                    this.selectText = selectText
                    this.setSureClick<SelectText> {
                        val select = it as TransModel
                        setLocalTransferView(select)
                    }
                }.show()
            }
        }

    }

    var address_list: ArrayList<AddressModel>? = null
    fun getPackListResult(orderParcelDetailModel: OrderParcelDetailModel?, addressList: ArrayList<AddressModel>) {
        this.orderParcelDetailModel = orderParcelDetailModel
//        address_list = orderParcelDetailModel?.address_list
        address_list = addressList
        val addressModel = address_list?.getOrNull(0)
        //设置收货地址
        setAddressView(addressModel)
        //设置订单详情
        setGoodsView(orderParcelDetailModel)
        //设置国际运输方式
        addressModel?.run {
            mViewModel.getInterTranser(addr_id, getWareHourseId(), isMingan())
        }
        bt_orderplace_submit.isEnabled = (orderParcelDetailModel != null)
    }

    override fun startObserver() {
        mViewModel.getPackListResultLiveData.observe(this, Observer {
            getPackListResult(it[0] as OrderParcelDetailModel?, it[1] as ArrayList<AddressModel>)
        })
        mViewModel.getInterTranserResultLiveData.observe(this, Observer {
            getInterTranserResult(it)
        })
        mViewModel.orderParcelResultLiveData.observe(this, Observer {
            orderParcelResult()
        })
    }

    fun getInterTranserResult(list: ArrayList<TransModel>?) {
        setInterTransferList(list)
    }

    fun orderParcelResult() {
        showMessage(R.string.申请打包成功)
        getEventBus().post(OrderParcelEvent())
        pop()
    }

    override val isRegisterEventBus: Boolean
        get() = true

    /**
     * 选择地址回调
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onSelectAddressChange(event: SelectAddressChange) {
        val addressId = ll_orderplace_address.addressModel?.addr_id ?: 0
        val addressModel = event.addressModel
        if (addressModel.addr_id != addressId) {
            mViewModel.getInterTranser(addressModel.addr_id, getWareHourseId(), isMingan())
        }
    }
}